<?php

namespace App\Models\Chanjet;

use App\Http\Models\Chanjet\TplusPurchaseInvoices;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TplusPurchaseInvoice extends Model
{
    protected $table = 'tplus_purchase_invoice';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];
    public static function getList(Request $request, $memberinfo, $isgetall)
    {
        $cpid = $memberinfo['cpid'] ?? 0;
        $where[] = ['cpid','=',$cpid];
        $partner_name = $request->partner_name;
        $voucher_code = $request->voucher_code;
        $start_time = $request->start_time;
        $end_time = $request->end_time;
        $pid = $request->pid;

        if($partner_name){
            $where[] = ['partner_name','=',$partner_name];
        }
        if($voucher_code){
            $where[] = ['voucher_code','=',$voucher_code];
        }
        if($pid){
            $where[] = ['id','=',$pid];
        }
        $query = self::with("info")->where($where)->orderBy("voucher_time","desc");
        if($start_time && $end_time){
            $query->whereBetween('voucher_time',[$start_time, $end_time]);
        }
        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            return ['list' => $list];
        }

    }
    public function info()
    {
        return $this->hasMany(TplusPurchaseInvoiceInfo::class,'main_id','id');
    }

    public static function getPartnerList(Request $request, $memberinfo, $isgetall){
        $cpid = $memberinfo['cpid'] ?? 0;
        $where[] = ['cpid','=',$cpid];
        $where[] = ['partner_name','<>',''];
        $query = self::where($where);
        $list = $query->select(["partner_name"])->distinct('partner_name')->get()->toArray();
        if(!empty($list)){
            foreach ($list as $key=>&$item){
                $item['id'] = $key+1;
            }
        }
        return ['list' => $list];
    }
}
